package com.tj.jinzao.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tj.jinzao.R;
import com.tj.jinzao.activity.ArticleDetailActivity;
import com.tj.jinzao.adapter.ArticleListItemAdapter;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseDataListFragment;
import com.tj.jinzao.callback.IListView;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.HistoryBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.presenter.ArticlePresenter;
import com.tj.jinzao.utils.SharedPreferencesUtils;
import com.tj.jinzao.widgets.EmptyView;
import com.tj.jinzao.widgets.LabelsView;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 社区文章列表
 * Created by wjy on 2019/1/1.
 */
public class SearchListFragment extends BaseDataListFragment<List<Article>, ArticlePresenter, Article> implements IListView<List<Article>>, TextWatcher {

    @BindView(R.id.et_keyword)
    EditText mKeyEditView;
    @BindView(R.id.fl_list_layout)
    View mListLayout;
    @BindView(R.id.labels)
    LabelsView labelsView;
    @BindView(R.id.labels_view)
    LabelsView labelsHot;
    @BindView(R.id.top_content)
    LinearLayout top_content;
    @BindView(R.id.top_1)
    LinearLayout top_1;
    @BindView(R.id.top_2)
    LinearLayout top_2;

    private LinkedList<String> list_tab=new LinkedList<>();
    private LinkedList<String> list_Hot=new LinkedList<>();

    private String mKeyword;

    public static SearchListFragment newInstance() {
        SearchListFragment fragment = new SearchListFragment();
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, "1");
            args.putInt(ARG_LOAD_ID, 1);
            args.putInt(ARG_LAYOUT_RES_ID, R.layout.fragment_search);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onRequestNoData(String message) {
        setEmptyDataView();
    }

    @Override
    protected ArticlePresenter createPresenter() {
        return new ArticlePresenter(this);
    }

    @Override
    protected void createView(LayoutInflater inflater, View view) {
        mKeyEditView.addTextChangedListener(this);
    }

    @Override
    protected RecyclerView.Adapter createAdapter() {
        return new ArticleListItemAdapter(mContext, mData);
    }

    @Override
    protected void requestData() {
        if (!TextUtils.isEmpty(mKeyword)) {
            mPresenter.searchArticle(mPageNo, mKeyword);
        } else {
            setEmptyDataView();
            top_content.setVisibility(View.VISIBLE);
        }

    }

    private void getHistory(){
        addSubscription(mApiService.getHistoryList(), new SubscriberCallBack<List<String>>(getActivity()) {
            @Override
            protected void onSuccess(List<String> list) {
                list_Hot.clear();
                list_Hot.addAll(list);
                labelsHot.setLabels(list_Hot);
                if(list_Hot.size()<=0){
                    top_2.setVisibility(View.GONE);
                }else {
                    top_2.setVisibility(View.VISIBLE);
                }
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }

    @OnClick(R.id.tv_cancel)
    public void cancel() {
        mKeyEditView.setText("");
        top_content.setVisibility(View.VISIBLE);
    }

    @Override
    protected void setEmptyDataView() {
        mEmptyView.setVisibility(View.VISIBLE);
        mEmptyView.setState(EmptyView.State.NO_DATA, "");
    }

    @Override
    public void onRequestSuccess(List<Article> Articles) {
        super.onRequestSuccess(Articles);
        if (mPageNo <= 1) {
            mData.clear();
        }
        mData.addAll(Articles);
        showListView();
        if(mData.size()>0){
            top_content.setVisibility(View.GONE);
            if(!list_tab.contains(mKeyword)){
                if(list_tab.size()>6){
                    list_tab.removeLast();
                }
                list_tab.addFirst(mKeyword);
            }
            HistoryBean historyBean= SharedPreferencesUtils.getBeanFromSp(getActivity(),"history","historyBean");
            if(historyBean!=null&&historyBean.getHistory()!=null&&historyBean.getHistory().size()>0){
                if(!historyBean.getHistory().contains(mKeyword)){
                    if(historyBean.getHistory().size()>6){
                        historyBean.getHistory().removeLast();
                    }
                    historyBean.getHistory().addFirst(mKeyword);
                    SharedPreferencesUtils.saveBean2Sp(getActivity(),historyBean,"history","historyBean");
                }
            }else {
                HistoryBean historyBeans=new HistoryBean();
                historyBeans.setHistory(list_tab);
                SharedPreferencesUtils.saveBean2Sp(getActivity(),historyBeans,"history","historyBean");
            }
            labelsView.setLabels(list_tab);
        }else {
            top_content.setVisibility(View.VISIBLE);
        }
    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
    }

    @Override
    protected boolean resolveData(List<Article> characters) {
        return false;
    }

    @Override
    protected void initData() {
        getHistory();
        list_tab.clear();
        HistoryBean historyBean= SharedPreferencesUtils.getBeanFromSp(getActivity(),"history","historyBean");
        if(historyBean!=null&&historyBean.getHistory()!=null&&historyBean.getHistory().size()>0){
            list_tab.addAll(historyBean.getHistory());
        }
        if(list_tab.size()<=0){
            top_1.setVisibility(View.GONE);
        }else {
            top_1.setVisibility(View.VISIBLE);
        }
        if(list_Hot.size()<=0){
            top_2.setVisibility(View.GONE);
        }else {
            top_2.setVisibility(View.VISIBLE);
        }
        labelsView.setLabels(list_tab, new LabelsView.LabelTextProvider<String>() {
            @Override
            public CharSequence getLabelText(TextView label, int position, String data) {
                return data;
            }
        });
        labelsView.setOnLabelSelectChangeListener(new LabelsView.OnLabelSelectChangeListener() {
            @Override
            public void onLabelSelectChange(TextView label, Object data, boolean isSelect, int position) {
                mKeyword = list_tab.get(position);
                mPageNo=1;
                mKeyEditView.setText(mKeyword);
            }
        });
        labelsHot.setLabels(list_Hot, new LabelsView.LabelTextProvider<String>() {
            @Override
            public CharSequence getLabelText(TextView label, int position, String data) {
                return data;
            }
        });
        labelsHot.setOnLabelSelectChangeListener(new LabelsView.OnLabelSelectChangeListener() {
            @Override
            public void onLabelSelectChange(TextView label, Object data, boolean isSelect, int position) {
                mKeyword = list_Hot.get(position);
                mPageNo=1;
                mKeyEditView.setText(mKeyword);
            }
        });


    }

    @Override
    protected void itemClicked(int position, Article data) {
        startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", data));
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(s.toString())) {
            mKeyword = s.toString();
            refresh();
        } else {
            mData.clear();
            showListView();
            top_content.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onRequestSuccessPage(int currentPage, int allPage, int allSize) {

    }

    @Override
    public void onReload(Object tag) {

    }
}
